<?php
set_include_path ( $_SERVER ['DOCUMENT_ROOT'] );
include_once 'admin/includes/functions/admin-functions.php';
global $DBobject, $SMARTY;

$referer = parse_url($_SERVER['HTTP_REFERER']);
if(!empty($_SESSION['user']['admin']['id']) ){
	if (!empty($_REQUEST['from']) && !empty($_REQUEST['to'])) {
		$fromDate = date("Y-m-d", strtotime( str_replace('/', '-', $_REQUEST['from'])));
		$toDate = date("Y-m-d", strtotime( str_replace('/', '-', $_REQUEST['to'])));
		$payments = array();
		$sql = "SELECT tbl_payment.*,	tbl_address.*, tbl_cart.*	
				FROM tbl_payment 
					LEFT JOIN tbl_cart ON payment_cart_id = cart_id  
					LEFT JOIN tbl_user ON payment_user_id = user_id  
					LEFT JOIN tbl_address ON payment_shipping_address_id = address_id 
					LEFT JOIN (SELECT cartitem_cart_id, COUNT(cartitem_id) AS cnt FROM tbl_cartitem WHERE cartitem_deleted IS NULL AND cartitem_cart_id <> '0' AND cartitem_product_id > 0 AND cartitem_class_flag = '0' GROUP BY cartitem_cart_id HAVING cnt > 1) AS tbl_cnt
					ON payment_cart_id = cartitem_cart_id
				WHERE payment_status = 'A' 
					AND payment_deleted IS NULL
					AND cartitem_cart_id IS NOT NULL
					AND DATE(payment_created) BETWEEN :from AND :to
				ORDER BY payment_created DESC";
	
		if($res = $DBobject->wrappedSql($sql, array(':from'=>$fromDate,':to'=>$toDate))){
			foreach ($res as $p){
				$sql = "SELECT * FROM tbl_cartitem WHERE cartitem_cart_id = :id AND cartitem_deleted IS NULL AND cartitem_cart_id <> '0' AND cartitem_product_id	 > 0 AND cartitem_class_flag = '0'";
				if($res2 = $DBobject->wrappedSql($sql,array(":id"=>$p['cart_id']))){
					$payments[$p['cart_id']] = $p;
					foreach ($res2 as $c){
						$payments[$p['cart_id']]['cartitems'][$c['cartitem_id']] = $c;
						$sql = "SELECT * FROM tbl_cartitem_attr WHERE cartitem_attr_cartitem_id	= :id AND cartitem_attr_deleted IS NULL AND cartitem_attr_cartitem_id <> '0'";
			      $payments[$p['cart_id']]['cartitems'][$c['cartitem_id']]['attributes'] = $DBobject->wrappedSql($sql,array(":id"=>$c['cartitem_id'] ));
					}
				}			
			}
	    $SMARTY->assign('payments',$payments);
		}
		$SMARTY->display('labels.tpl');
	}
}
die();
